﻿/**
 * 页面通用验证类
 *
 * Usage: 
 * 1: 在页面中引入 validate.js (依赖prototype.js , 版本1.5以上)
 *
 * 2: 在input,select 中加入gbname(字段中文名), validator属性
 *    validator中可以添加多个验证规则,以逗号隔开
 *    可用的验证规则包括 (required, len, date, num) , 其中len需要指定最大长度
 *   例子如下:
 *   <select name="marriageStatus" class="input_select" gbname="婚姻状况" validator="len(2)">
 *   <input name="familyName" type="text" class="input" gbname="姓名" validator="required,len(30)" >
 *
 * 3: 调用方法
 *  a:在form元素中, 添加提交时的验证
 *   <form name="form1" action="employeeFamilyEdit.action" method="post" onsubmit="return validate();" >
 *
 *  b: 自已定义 customValidate(任意命名), 然后调用 validate方法
 *    function customValidate() {
 *       validateIdentity();
 *       validateUnitiveCode();
 *       validateClass();
 *       .....;
 *       return validate();
 *    }
 *
 *
 */

function validate() {
  validator = new Validator();
  return validator.validate();
}

var Validator = Class.create({

  trim : function(s) {
    return s.replace(/(^\s+)|(\s+$)/g, "");
  },

  checkRequired: function(ele,gbname) {
    if (ele.value == null || this.trim(ele.value) == "") {
      addFieldError(ele.name, "请输入" + gbname);
      ele.value = "";
      ele.focus();
      return false;
    }
    return true;
  },

  isBlank: function(s) {
    var re = /^\s*$/g;
    return re.test(s);
  } ,

  compareDate: function(elem1, elem2) {
    if (elem1.value != "" && elem2.value != "") {
      var date1;
      var date2;
      try {
        date1 = elem1.value.split('-');
        date2 = elem2.value.split('-');
      } catch (e) {
        date1 = elem1.split('-');
        date2 = elem2.split('-');
      }
      if (eval(date1[0]) > eval(date2[0])) {
        return 1;
      } else if (eval(date1[0]) == eval(date2[0])) {
        if (eval(date1[1]) > eval(date2[1])) {
          return 1;
        } else if (eval(date1[1]) == eval(date2[1])) {
          if (eval(date1[2]) > eval(date2[2])) {
            return 1;
          } else if (eval(date1[2]) == eval(date2[2])) {
            return 0;
          } else {
            return -1;
          }
        } else {
          return -1;
        }
      } else {
        return -1;
      }
    }
  },

  checkDate: function(elem, field) {
    if (this.isBlank(elem.value))
      return true;
    var DateValue = "";
    var seperator = "-";
    var day;
    var month;
    var year;
    var leap = 0;
    var err = 0;
    err = 0;
    DateValue = elem.value;

    var re = /[^0-9\-]+/gi;

    DateValue = DateValue.replace(re, ""); // 去除所有数字和'-'以外的字符

    var parts = DateValue.split('-');

    VALIDATION: {
      var len = parts.length;
      if (len != 3) {
        err = 19;
        break VALIDATION;
      }
      if (parts[0].length != 4) {
        err = 100;
        break VALIDATION;
      }
      year = parseInt(this.trim(parts[0]), 10);

      if ((isNaN(year)) || (year == 0)) {
        err = 20;
        break VALIDATION;
      }
      /* Validation of month */
      month = parseInt(this.trim(parts[1]), 10);
      if ((isNaN(month)) || (month < 1) || (month > 12)) {
        err = 21;
        break VALIDATION;
      }
      /* Validation of day */
      day = parseInt(this.trim(parts[2]), 10);
      if ((isNaN(day)) || (day < 1)) {
        err = 22;
        break VALIDATION;

      }

      /* Validation leap-year / february / day */
      if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) {
        leap = 1;
      }
      if ((month == 2) && (leap == 1) && (day > 29)) {
        err = 23;
        break VALIDATION;
      }
      if ((month == 2) && (leap != 1) && (day > 28)) {
        err = 24;
        break VALIDATION;
      }
      /* Validation of other months */
      if ((day > 31)
          && ((month == "01") || (month == "03") || (month == "05")
              || (month == "07") || (month == "08")
              || (month == "10") || (month == "12"))) {
        err = 25;
        break VALIDATION;
      }
      if ((day > 30)
          && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) {
        err = 26;
        break VALIDATION;
      }
      /* if 00 ist entered, no error, deleting the entry */
      if ((day == 0) && (month == 0) && (year == 00)) {
        err = 0;
        day = "";
        month = "";
        year = "";
        seperator = "";
      }
    }
    /* if no error, write the completed date to Input-elem (e.g. 13.12.2001) */
    if (err == 0) {
      if (this.compareDate(year + seperator + month + seperator + day, "1900"
          + seperator + "1" + seperator + "1") < 0) {
        // alert(field + '的值不能小于1900-1-1');
        addFieldError(elem, field + "的值必须在1900-01-01到2038-01-01之间");
        elem.select();
        return false;
      }
      if (this.compareDate("2038" + seperator + "1" + seperator + "1", year
          + seperator + month + seperator + day) < 0) {
        addFieldError(elem, field + "的值必须在1900-01-01到2038-01-01之间");
        elem.select();
        return false;
      }
      elem.value = year + seperator + month + seperator + day;

    } else {
      addFieldError(elem, '要求' + field + '的格式为yyyy-mm-dd，并请注意月份与日期的有效范围');
      elem.select();
      return false;
    }
    return true;
  },

  checkNum: function(elem, field) {
    if (this.isBlank(elem.value))
      return true;

    val = elem.value;
    var pattern = /[^0-9.]/;
    if (pattern.test(val)) {
      addFieldError(elem, field + "只能输入数值型数据！");
      elem.value = '';
      elem.focus();
      return false;
    }
    return true;
  } ,

  checkOverLen : function(elem, maxlen, field) {
    var len;
    var i;
    len = 0;
    var val = this.trim(elem.value);
    var maxlength = parseInt(maxlen);
    var length = val.length;
    for (i = 0; i < length; i++) {
      if (val.charCodeAt(i) > 255)
        len += 2;
      else
        len++;
    }
    elem.value = val;
    if (len > maxlength) {
      addFieldError(elem, field + "长度超过范围,允许范围为0-" + maxlength);
      elem.focus();
      return false;
    }
    return true;
  } ,

  validate: function() {
    var elements = $$("*[validator]");
    for ( var i = 0; i < elements.length; i++) {
      var validators = elements[i].getAttribute("validator").split(",");
      var gbname = elements[i].getAttribute("gbname");
      for ( var j = 0; j < validators.length; j++) {
        valid = true;
        if (validators[j] == "required") {
          valid=this.checkRequired(elements[i], gbname);
        } else if (validators[j] == "date") {
          valid=this.checkDate(elements[i], gbname);
        } else if (validators[j] == "num") {
          valid=this.checkNum(elements[i], gbname);
        } else if (validators[j].indexOf("len") > -1) {
          var len = validators[j].substring(validators[j].indexOf("(") + 1, validators[j].indexOf(")"));
          valid=this.checkOverLen(elements[i], parseInt(len), gbname);
        }
        if (!valid) return false;
      }
    }
    return true;
	}
});


